﻿#include "mainfunction.h"
#include "ui_mainfunction.h"

MainFunction::MainFunction(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainFunction),
    ModelRes(new QStandardItemModel(this)),
    ModelDB(new QStandardItemModel(this))
{
    ui->setupUi(this);
    capStatus = true;
    capModelId = 0;
    //隐藏标题栏
    this->setWindowFlags(Qt::FramelessWindowHint);

    //菜单栏
    QMenu *menu = new QMenu(this);
    QAction* A1 = menu->addAction("个人中心");
    QAction* A2 = menu->addAction("退出登录");
    QAction* A3 = menu->addAction("退出系统");
    menu->setStyleSheet("QMenu{"
                            "background:rgba(255,255,255,1);"
                            "border:none;"
                        "}"
                        "QMenu::item{"
                            "padding:10px 20px;"
                            "color:rgba(51,51,51,1);"
                            "font-size:12px;"
                        "}"
                        "QMenu::item:hover{"
                            "background-color:#409CE1;"
                        "}"
                        "QMenu::item:selected{"
                            "background-color:#409CE1;"
                        "}");
    connect(A1, SIGNAL(triggered()), this, SLOT(ClickMenu1()));
    connect(A2, SIGNAL(triggered()), this, SLOT(ClickMenu2()));
    connect(A3, SIGNAL(triggered()), this, SLOT(ClickMenu3()));
    ui->pushButtonName->setMenu(menu);

    //隐藏tabbar
    ui->tabWidget->tabBar()->setHidden(true);

    //默认第一页面
    ui->tabWidget->setCurrentIndex(0);

    //read only
    ui->lineEditAddress->setReadOnly(true);
    ui->lineEditCard->setReadOnly(true);
    ui->lineEditCardNum->setReadOnly(true);
    ui->lineEditName->setReadOnly(true);
    ui->lineEditPhone->setReadOnly(true); //to min zu
    ui->lineEditSex->setReadOnly(true);

    ConnectSlots();
}

MainFunction::~MainFunction()
{
    delete ModelRes;
    delete ModelDB;
    delete ui;
}

void MainFunction::ConnectSlots()
{

}

//tarbar换成按钮
void MainFunction::on_pushButtonCamera_clicked()
{
    ui->tabWidget->setCurrentIndex(0);
}

void MainFunction::on_pushButtonCameraLevel_clicked()
{
    ui->tabWidget->setCurrentIndex(2);
    ui->tabWidget_2->setCurrentIndex(0);
}

void MainFunction::on_pushButtonCameraPicCmp_clicked()
{
    ui->tabWidget->setCurrentIndex(1);
}

void MainFunction::on_pushButtonCameraLog_clicked()
{
    ui->tabWidget->setCurrentIndex(3);
}

//最小化
void MainFunction::on_pushButtonMin_clicked()
{
    this->showMinimized();
}

//关闭界面
void MainFunction::on_pushButtonQuit_clicked()
{
    emit closeAll();
}

//个人中心
void MainFunction::ClickMenu1()
{
    ui->tabWidget->setCurrentIndex(4);
}

//退出登录
void MainFunction::ClickMenu2()
{
    emit toLogin();
}

//退出系统
void MainFunction::ClickMenu3()
{
    emit closeAll();
}

//隐藏标题框移动
void MainFunction::mousePressEvent(QMouseEvent *e)
{
    last=e->globalPosition().toPoint();
}

void MainFunction::mouseMoveEvent(QMouseEvent *e)
{
    int dx = e->globalPosition().toPoint().x() - last.x();
    int dy = e->globalPosition().toPoint().y() - last.y();
    last = e->globalPosition().toPoint();
    move(x()+dx, y()+dy);
}

void MainFunction::mouseReleaseEvent(QMouseEvent *e)
{
    int dx = e->globalPosition().toPoint().x() - last.x();
    int dy = e->globalPosition().toPoint().y() - last.y();
    move(x()+dx, y()+dy);
}

//手势识别 三级验证
void MainFunction::on_pushButtonStart_4_clicked()
{
    if (!allTools::getCap()->isOpened())
    {
        allTools::getCap()->open(0);
        if(!allTools::getCap()->isOpened()) qDebug() << "Can not open a camera\n";
    }
    int res = 0;
    Mat img,com;
    QImage _img, __img;
    // Model Init
    ModelRes->clear();
    QStringList headerLable1;
    headerLable1 << "HandInfer Verification";
    ModelRes->setHorizontalHeaderLabels(headerLable1);
    ModelRes->setRowCount(1);
    ModelRes->setColumnCount(1);
    //tabview init
    ui->tableResult_4->verticalHeader()->setHidden(true); //去除序列号
    ui->tableResult_4->setFocusPolicy(Qt::NoFocus); // 去除选中虚线框
    ui->tableResult_4->horizontalHeader()->setStretchLastSection(true); //表头填充
    QString res_s = "";
    int times = 0;
    bool flag = false;

    //随机数
    int ra = QRandomGenerator::global()->bounded(1,5);

    while (true)
    {
        if(capStatus == false) {capStatus = true; break;}
        *allTools::getCap() >> img;
        if (img.empty()) break;
        cv::flip(img, img, 1);

        if(!flag)
        {
            com = allTools::handInfer(img, &res);
            if(res == ra)
            {
                if(times >= 3)
                {
                    QMessageBox OK(this);
                    OK.setWindowTitle("提示");
                    OK.setText("验证成功！");
                    OK.addButton("确定",QMessageBox::AcceptRole);
                    if(OK.exec() == QMessageBox::AcceptRole) {}
                    flag = true;
                }
                else
                  times ++;
            }
        }
        else
        {
            //function OK
            // func(fd,fr,img, UserPic);
            allTools::drawFaceInfo(img, UserPic);
        }

        ModelRes->setData(ModelRes->index(0, 0), "请做出第" + QString::number(ra) + "种手势！", Qt::DisplayRole);
        ModelRes->item(0,0)->setTextAlignment(Qt::AlignCenter); //内容居中
        ui->tableResult_4->setModel(ModelRes);

        cvtColor(com, com, cv::COLOR_BGR2RGB);
        _img  = QImage((const unsigned char*)com.data, com.cols, com.rows, com.step, QImage::Format_RGB888);
        __img = _img.scaled(ui->previewlabel_4->width(),ui->previewlabel_4->height());
        ui->previewlabel_4->setPixmap(QPixmap::fromImage(__img));

        cv::waitKey(0);
    }
}

void MainFunction::on_pushButtonStop_4_clicked()
{
    ui->previewlabel_4->clear();
    capStatus = false;
}

//摄像头检测
void MainFunction::on_pushButtonOpen_clicked()
{
    capModelId = 0;
    if (!allTools::getCap()->isOpened())
    {
        allTools::getCap()->open(0);
        if(!allTools::getCap()->isOpened()) qDebug() << "Can not open a camera\n";
    }
    Mat img,com;
    QImage _img, __img;

    // Model Init
    ModelRes->clear();
    QStringList headerLable1;
    headerLable1 << "Camera Result";
    ModelRes->setHorizontalHeaderLabels(headerLable1);
    ModelRes->setRowCount(1);
    ModelRes->setColumnCount(1);
    //tabview init
    ui->lableRecord->verticalHeader()->setHidden(true); //去除序列号
    ui->lableRecord->setFocusPolicy(Qt::NoFocus); // 去除选中虚线框
    ui->lableRecord->horizontalHeader()->setStretchLastSection(true); //表头填充
    QString res_s = "";

    while (true)
    {
        if(capStatus == false) {capStatus = true; break;}
        *allTools::getCap() >> img;
        if (img.empty()) break;
        cv::flip(img, img, 1);

        if(capModelId == 0)  //普通摄像头 <质量>
        {
            QMap<QString,QString> f = allTools::getQualityAssessorInfo(img);
            res_s = QString::fromUtf8("图片质量结果 ");
            if(f.empty()) //not found face!
            {
                ModelRes->setData(ModelRes->index(0, 0), "未检测到人脸！", Qt::DisplayRole);
                ModelRes->item(0,0)->setTextAlignment(Qt::AlignCenter); //内容居中
            }
            else
            {
                qDebug() << f.size();
                ModelRes->setRowCount(5);
                ModelRes->setData(ModelRes->index(0, 0), "图片亮度：" + f["bri"], Qt::DisplayRole);
                ModelRes->item(0,0)->setTextAlignment(Qt::AlignCenter); //内容居中
                ModelRes->setData(ModelRes->index(1, 0), "图片清晰度：" +f["qxd"], Qt::DisplayRole);
                ModelRes->item(1,0)->setTextAlignment(Qt::AlignCenter); //内容居中
                ModelRes->setData(ModelRes->index(2, 0), "图片姿态：" +f["zt"], Qt::DisplayRole);
                ModelRes->item(2,0)->setTextAlignment(Qt::AlignCenter); //内容居中
                ModelRes->setData(ModelRes->index(3, 0), "图片面部完整：" +f["face"], Qt::DisplayRole);
                ModelRes->item(3,0)->setTextAlignment(Qt::AlignCenter); //内容居中
                ModelRes->setData(ModelRes->index(4, 0), "图片分辨率：" +f["fps"], Qt::DisplayRole);
                ModelRes->item(4,0)->setTextAlignment(Qt::AlignCenter); //内容居中
            }
            allTools::drawFaceInfo(img, UserPic);
            com = img;
        }
        else if(capModelId == 1) //关键点检测 68点
        {
            com = allTools::getPoint68(img);
            //com = img;
            res_s = QString::fromUtf8("当前为68个关键点功能 ");
            ModelRes->setData(ModelRes->index(0, 0), res_s, Qt::DisplayRole);
            ModelRes->item(0,0)->setTextAlignment(Qt::AlignCenter); //内容居中
        }
        else if(capModelId == 2) //精细分割
        {
            com = allTools::PPMatting("CPU", img);
            res_s = QString::fromUtf8("当前为精细分割功能 ");
            ModelRes->setData(ModelRes->index(0, 0), res_s, Qt::DisplayRole);
            ModelRes->item(0,0)->setTextAlignment(Qt::AlignCenter); //内容居中
        }
        ui->lableRecord->setModel(ModelRes);


        cvtColor(com, com, cv::COLOR_BGR2RGB);
        _img  = QImage((const unsigned char*)com.data, com.cols, com.rows, com.step, QImage::Format_RGB888);
        __img = _img.scaled(ui->lableCamera->width(),ui->lableCamera->height());
        ui->lableCamera->setPixmap(QPixmap::fromImage(__img));

        cv::waitKey(0);

    }
}

//关闭摄像头 cap检测
void MainFunction::on_pushButtonClose_clicked()
{
    ui->lableCamera->clear();
    capStatus = false;
}

//关键点检测
void MainFunction::on_pushButtonPoint_clicked()
{
    if(capModelId != 1) {capModelId = 1;}
    else if(capModelId == 1) {capModelId = 0;
        //ModelRes->clear();
    }

}

//精细分割
void MainFunction::on_pushButtonSegment_clicked()
{
    if(capModelId != 2) capModelId = 2;
    else if(capModelId == 2)
    {
        capModelId = 0;
        //ModelRes->clear();
    }

}

//四级验证 表情识别 验证
void MainFunction::on_pushButtonStart_2_clicked()
{
    if (!allTools::getCap()->isOpened())
    {
        allTools::getCap()->open(0);
        if(!allTools::getCap()->isOpened()) qDebug() << "Can not open a camera\n";
    }
    Mat img;
    QString res_s = UserInfo["emotion"];
    QImage _img, __img;
    // Model Init
    ModelRes->clear();
    QStringList headerLable1;
    headerLable1 << "Emotion Verification";
    ModelRes->setHorizontalHeaderLabels(headerLable1);
    ModelRes->setRowCount(1);
    ModelRes->setColumnCount(1);
    //tabview init
    ui->tableResult_2->verticalHeader()->setHidden(true); //去除序列号
    ui->tableResult_2->setFocusPolicy(Qt::NoFocus); // 去除选中虚线框
    ui->tableResult_2->horizontalHeader()->setStretchLastSection(true); //表头填充
    int res = 0;
    bool flag = false;
    int times = 0;
    QTime time_t;
    int f = 0; // open time_t
    while (true)
    {
        if(res_s.isEmpty())
        {
            QMessageBox t(this);
            t.setWindowTitle("提示");
            t.setText("请先录入表情！");
            t.addButton("确定",QMessageBox::AcceptRole);
            if(t.exec() == QMessageBox::AcceptRole) {}
            break;
        }
        if(capStatus == false) {capStatus = true; break;}
        *allTools::getCap() >> img;
        if (img.empty()) break;
        cv::flip(img, img, 1);

        //TabView 插入数据
        ModelRes->setData(ModelRes->index(0, 0), "请在5s内做出录入的表情！", Qt::DisplayRole);
        ModelRes->item(0,0)->setTextAlignment(Qt::AlignCenter); //内容居中
        ui->tableResult_2->setModel(ModelRes);

        if(!flag)
        {
            if(!f)
            {
                time_t = QTime::currentTime();
                f = 1;
            }

            res = allTools::emotion("CPU", img);
            if(res == res_s.toInt())
            {
                if(times >= 3)
                {
                    QMessageBox OK(this);
                    OK.setWindowTitle("提示");
                    OK.setText("验证成功！");
                    OK.addButton("确定",QMessageBox::AcceptRole);
                    if(OK.exec() == QMessageBox::AcceptRole) {}
                    flag = true;
                }
                else times ++;
            }
            else //时间到导入日志
            {
                QTime _time_t = QTime::currentTime();
                if( _time_t.secsTo(time_t) <= -5 )
                {
                    //记录日志
                    QDate tt = QDate::currentDate();
                    allTools::insertLogInfo(tt.toString("yyyy.MM.dd"), UserInfo["id"], "恶意表情攻击", "192.168.0.5");

                    QMessageBox OK(this);
                    OK.setWindowTitle("提示");
                    OK.setText("未在规定时间内做出表情！记录日志！");
                    OK.addButton("确定",QMessageBox::AcceptRole);
                    if(OK.exec() == QMessageBox::AcceptRole) {}
                    f = 0;
                    ui->previewlabel_2->clear();
                    break;
                }

            }
        }
        else
        {
            //function OK
            // func(fd,fr,img, UserPic);
            allTools::drawFaceInfo(img, UserPic);
        }

        cvtColor(img, img, cv::COLOR_BGR2RGB);
        _img  = QImage((const unsigned char*)img.data, img.cols, img.rows, img.step, QImage::Format_RGB888);
        __img = _img.scaled(ui->previewlabel_2->width(),ui->previewlabel_2->height());
        ui->previewlabel_2->setPixmap(QPixmap::fromImage(__img));


        cv::waitKey(0);
    }
}

void MainFunction::on_pushButtonStop_2_clicked()
{
    ui->previewlabel_2->clear();
    capStatus = false;
}

// 二级验证 眼球跟踪
void MainFunction::on_pushButtonStart_3_clicked()
{
    if (!allTools::getCap()->isOpened())
    {
        allTools::getCap()->open(0);
        if(!allTools::getCap()->isOpened()) qDebug() << "Can not open a camera\n";
    }
    Mat img;
    QString res_s = "";
    QImage _img, __img;
    // Model Init
    ModelRes->clear();
    QStringList headerLable1;
    headerLable1 << "Eye Verification";
    ModelRes->setHorizontalHeaderLabels(headerLable1);
    ModelRes->setRowCount(1);
    ModelRes->setColumnCount(1);
    //tabview init
    ui->tableResult_3->verticalHeader()->setHidden(true); //去除序列号
    ui->tableResult_3->setFocusPolicy(Qt::NoFocus); // 去除选中虚线框
    ui->tableResult_3->horizontalHeader()->setStretchLastSection(true); //表头填充

    int res = 0;
    bool flag = false;
    //随机数
    int ra = QRandomGenerator::global()->bounded(8,9);
    while (true)
    {
        if(capStatus == false) {capStatus = true; break;}
        *allTools::getCap() >> img;
        if (img.empty()) break;
        cv::flip(img, img, 1);

        //TabView 插入数据
        QString t = "";
        if(ra == 8) t = "左";
        else if(ra == 9) t = "右";

        ModelRes->setData(ModelRes->index(0, 0), "请眼球向" + t + "移动！", Qt::DisplayRole);
        ModelRes->item(0,0)->setTextAlignment(Qt::AlignCenter); //内容居中
        ui->tableResult_3->setModel(ModelRes);

        if(!flag)
        {
            res = allTools::getEyeRotateId(img);

            if(res == ra)
            {
                QMessageBox OK(this);
                OK.setWindowTitle("提示");
                OK.setText("验证成功！");
                OK.addButton("确定",QMessageBox::AcceptRole);
                if(OK.exec() == QMessageBox::AcceptRole) {}
                flag = true;
            }
//            if(res == 0)
//            {
//                res_s = QString::fromUtf8("眼球未移动！ ");
//            }
//            else if(res == 8)
//            {
//                res_s = QString::fromUtf8("眼球向左移动！ ");
//            }
//            else if(res == 9) // OK
//            {
//                res_s = QString::fromUtf8("眼球向右移动！ ");

//            }
        }
        else
        {
            //function OK
            // func(fd,fr,img, UserPic);
           allTools::drawFaceInfo(img, UserPic);
        }

        cvtColor(img, img, cv::COLOR_BGR2RGB);
        _img  = QImage((const unsigned char*)img.data, img.cols, img.rows, img.step, QImage::Format_RGB888);
        __img = _img.scaled(ui->previewlabel_3->width(),ui->previewlabel_3->height());
        ui->previewlabel_3->setPixmap(QPixmap::fromImage(__img));

        cv::waitKey(0);
    }

}

void MainFunction::on_pushButtonStop_3_clicked()
{
    ui->previewlabel_3->clear();
    capStatus = false;
}

//五级验证 面部动作识别
void MainFunction::on_pushButtonDetect_clicked()
{
    if (!allTools::getCap()->isOpened())
    {
        allTools::getCap()->open(0);
        if(!allTools::getCap()->isOpened()) qDebug() << "Can not open a camera\n";
    }
    Mat img;
    QString res_s = UserInfo["action"];
    QImage _img, __img;
    // Model Init
    ModelRes->clear();
    QStringList headerLable1;
    headerLable1 << "FaceAction Verification";
    ModelRes->setHorizontalHeaderLabels(headerLable1);
    ModelRes->setRowCount(1);
    ModelRes->setColumnCount(1);

    //tabview init
    ui->tableResult_5->verticalHeader()->setHidden(true); //去除序列号
    ui->tableResult_5->setFocusPolicy(Qt::NoFocus); // 去除选中虚线框
    ui->tableResult_5->horizontalHeader()->setStretchLastSection(true); //表头填充

    int res = 0;
    int times = 0;
    int _times = 1;
    int f = 0;
    QTime time_t;
    while (true)
    {
        if(res_s.isEmpty())
        {
            QMessageBox t(this);
            t.setWindowTitle("提示");
            t.setText("请先录入动作！");
            t.addButton("确定",QMessageBox::AcceptRole);
            if(t.exec() == QMessageBox::AcceptRole) {}
            break;
        }
        if(capStatus == false) {capStatus = true; break;}
        *allTools::getCap() >> img;
        if (img.empty()) break;
        cv::flip(img, img, 1);

        if(_times == 1)
        {
            if(!f)  //开始计时
            {
                f = 1;
                time_t = QTime::currentTime();
            }

            //TabView 插入数据
            ModelRes->setData(ModelRes->index(0, 0), "请在5s内进行第一个动作!", Qt::DisplayRole);
            ModelRes->item(0,0)->setTextAlignment(Qt::AlignCenter); //内容居中
            ui->tableResult_5->setModel(ModelRes);

            res = allTools::getFaceActionId(img);
            if(char('0' + res) == res_s[0] )
            {
                times ++;
                if(times >= 1)
                {
                    times = 0;
                    _times ++;
                    ui->checkBox->setChecked(true);
                    f = 0;
                }

            }
            else //记录日志
            {
                QTime _time_t = QTime::currentTime();
                if( _time_t.secsTo(time_t) <= -5 )
                {
                    //update action
                    QDate tt = QDate::currentDate();
                    allTools::insertLogInfo(tt.toString("yyyy.MM.dd"), UserInfo["id"], "恶意动作攻击", "192.168.1.2");

                    QMessageBox OK(this);
                    OK.setWindowTitle("提示");
                    OK.setText("未在规定时间内做出动作！记录日志！");
                    OK.addButton("确定",QMessageBox::AcceptRole);
                    if(OK.exec() == QMessageBox::AcceptRole) {}
                    f = 0;
                    ui->previewlabel_5->clear();
                    break;
                }
            }
        }
        else if(_times == 2)
        {
            if(!f)
            {
                f = 1;
                time_t = QTime::currentTime();
            }

            //TabView 插入数据
            ModelRes->setData(ModelRes->index(0, 0), "请在5s内进行第二个动作!", Qt::DisplayRole);
            ModelRes->item(0,0)->setTextAlignment(Qt::AlignCenter); //内容居中
            ui->tableResult_5->setModel(ModelRes);

            res = allTools::getFaceActionId(img);
            if(char('0' + res) == res_s[1] )
            {
                times ++;
                if(times >= 1)
                {
                    times = 0;
                    _times ++;
                    ui->checkBox->setChecked(false);
                    ui->checkBox_2->setChecked(true);
                    f = 0;
                }

            }
            else
            {
                QTime _time_t = QTime::currentTime();
                if( _time_t.secsTo(time_t) <= -5 )
                {
                    //update action
                    QDate tt = QDate::currentDate();
                    allTools::insertLogInfo(tt.toString("yyyy.MM.dd"), UserInfo["id"], "恶意动作攻击", "192.168.1.2");

                    QMessageBox OK(this);
                    OK.setWindowTitle("提示");
                    OK.setText("未在规定时间内做出动作！记录日志！");
                    OK.addButton("确定",QMessageBox::AcceptRole);
                    if(OK.exec() == QMessageBox::AcceptRole) {}
                    f = 0;
                    ui->previewlabel_5->clear();
                    break;
                }
            }

        }
        else if(_times == 3)
        {
            if(!f)
            {
                f = 1;
                time_t = QTime::currentTime();
            }

            //TabView 插入数据
            ModelRes->setData(ModelRes->index(0, 0), "请在5s内进行第三个动作!", Qt::DisplayRole);
            ModelRes->item(0,0)->setTextAlignment(Qt::AlignCenter); //内容居中
            ui->tableResult_5->setModel(ModelRes);

            res = allTools::getFaceActionId(img);
            if(char('0' + res) == res_s[2] )
            {
                times ++;
                if(times >= 1)
                {
                    times = 0;
                    _times ++;
                    ui->checkBox_2->setChecked(false);
                    ui->checkBox_3->setChecked(true);
                    f = 0;
                    QMessageBox t(this);
                    t.setWindowTitle("提示");
                    t.setText("验证成功！");
                    t.addButton("确定",QMessageBox::AcceptRole);
                    if(t.exec() == QMessageBox::AcceptRole) {}
                }

            }
            else
            {
                QTime _time_t = QTime::currentTime();
                if( _time_t.secsTo(time_t) <= -5 )
                {
                    //update action
                    QDate tt = QDate::currentDate();
                    allTools::insertLogInfo(tt.toString("yyyy.MM.dd"), UserInfo["id"], "恶意动作攻击", "192.168.1.2");

                    QMessageBox OK(this);
                    OK.setWindowTitle("提示");
                    OK.setText("未在规定时间内做出动作！记录日志！");
                    OK.addButton("确定",QMessageBox::AcceptRole);
                    if(OK.exec() == QMessageBox::AcceptRole) {}
                    f = 0;
                    ui->previewlabel_5->clear();
                    break;
                }
            }
        }
        else if(_times == 4)
        {
            //function OK
            // func(fd,fr,img, UserPic);
            ui->checkBox_3->setChecked(false);
            allTools::drawFaceInfo(img, UserPic);
        }

//        if(res == 1) //EYE_LEFT_BLINK_ACTION
//        {
//            res_s = QString::fromUtf8("当前动作为:眨左眼 ");
//        }
//        else if(res == 2) //EYE_RIGHT_BLINK_ACTION
//        {
//            res_s = QString::fromUtf8("当前动作为:眨右眼 ");
//        }
//        else if(res == 3) //EYE_ALL_BLINK_ACTION
//        {
//            res_s = QString::fromUtf8("当前动作为:眨双眼 ");
//        }
//        else if(res == 4) //TURN_LEFT_ACTION
//        {
//            res_s = QString::fromUtf8("当前动作为:左转头 ");
//        }
//        else if(res == 5) //TURN_RIGHT_ACTION
//        {
//            res_s = QString::fromUtf8("当前动作为:右转头 ");
//        }
//        else if(res == 6) //TURN_UP_ACTION
//        {
//            res_s = QString::fromUtf8("当前动作为:抬头 ");
//        }
//        else if(res == 7) //MOUTH_ACTION
//        {
//            res_s = QString::fromUtf8("当前动作为:张嘴 ");
//        }

        cvtColor(img, img, cv::COLOR_BGR2RGB);
        _img  = QImage((const unsigned char*)img.data, img.cols, img.rows, img.step, QImage::Format_RGB888);
        __img = _img.scaled(ui->previewlabel_5->width(),ui->previewlabel_5->height());
        ui->previewlabel_5->setPixmap(QPixmap::fromImage(__img));

        cv::waitKey(0);
    }
}

void MainFunction::on_pushButtonGetAction_clicked()
{
    ui->previewlabel_5->clear();
    capStatus = false;
}

//一级验证 活体检测
void MainFunction::on_pushButtonStart_clicked()
{
    if (!allTools::getCap()->isOpened())
    {
        allTools::getCap()->open(0);
        if(!allTools::getCap()->isOpened()) qDebug() << "Can not open a camera\n";
    }
    Mat img;
    QString res_s = "";
    QImage _img, __img;
    // Model Init
    ModelRes->clear();
    QStringList headerLable1;
    headerLable1 << "FaceAction Result";
    ModelRes->setHorizontalHeaderLabels(headerLable1);
    ModelRes->setRowCount(1);
    ModelRes->setColumnCount(1);

    //tabview init
    ui->tableResult_1->verticalHeader()->setHidden(true); //去除序列号
    ui->tableResult_1->setFocusPolicy(Qt::NoFocus); // 去除选中虚线框
    ui->tableResult_1->horizontalHeader()->setStretchLastSection(true); //表头填充

    while (true)
    {
        if(capStatus == false) {capStatus = true; break;}
        *allTools::getCap() >> img;
        if (img.empty()) break;
        cv::flip(img, img, 1);
        res_s = QString::fromStdString(allTools::getFaceAntiSpoofingStatus(img));

        if(res_s.isEmpty())
        {
            res_s = QString::fromUtf8("未检测到人脸！ ");
        }
        else if(res_s == "spoof")
        {
            res_s = QString::fromUtf8("检测到假体！ ");
        }
        else if(res_s == "real")
        {
            res_s = QString::fromUtf8("为真实人脸 ");
        }
        else if(res_s == "fuzzy")
        {
            res_s = QString::fromUtf8("无法检测！ ");
        }
        else if(res_s == "detecting")
        {
            res_s = QString::fromUtf8("正在检测... ");
        }
        else if(res_s == "more")
        {
            res_s = QString::fromUtf8("图中人脸过多! ");
        }

        //TabView 插入数据
        ModelRes->setData(ModelRes->index(0, 0), res_s, Qt::DisplayRole);
        ModelRes->item(0,0)->setTextAlignment(Qt::AlignCenter); //内容居中
        ui->tableResult_1->setModel(ModelRes);

        cvtColor(img, img, cv::COLOR_BGR2RGB);
        _img  = QImage((const unsigned char*)img.data, img.cols, img.rows, img.step, QImage::Format_RGB888);
        __img = _img.scaled(ui->previewlabel->width(),ui->previewlabel->height());
        ui->previewlabel->setPixmap(QPixmap::fromImage(__img));

        cv::waitKey(0);
    }
}

void MainFunction::on_pushButtonStop_clicked()
{
    ui->previewlabel->clear();
    capStatus = false;
}

// 个人信息写入
void MainFunction::putUserInfo()
{
    ui->lineEditAddress->setText(UserInfo["address"]);
    ui->lineEditCard->setText("身份证");
    ui->lineEditCardNum->setText(UserInfo["id"]);
    ui->lineEditName->setText(UserInfo["name"]);
    ui->lineEditPhone->setText(UserInfo["nation"]); //to min zu
    ui->lineEditSex->setText(UserInfo["sex"]);

    cv::Mat imgPeople = cv::imread(UserInfo["idCardImagePath"].toStdString());
    cv::Mat imgUser = cv::imread(UserInfo["imagePath"].toStdString());
    QImage _img, __img;
    cvtColor(imgPeople, imgPeople, cv::COLOR_BGR2RGB);
    _img  = QImage((const unsigned char*)imgPeople.data, imgPeople.cols, imgPeople.rows, imgPeople.step, QImage::Format_RGB888);
    __img = _img.scaled(ui->labelIDFacepic->width(),ui->labelIDFacepic->height());
    ui->labelIDFacepic->setPixmap(QPixmap::fromImage(__img));

    cvtColor(imgUser, imgUser, cv::COLOR_BGR2RGB);
    _img  = QImage((const unsigned char*)imgUser.data, imgUser.cols, imgUser.rows, imgUser.step, QImage::Format_RGB888);
    __img = _img.scaled(ui->labelIDFacepic_2->width(),ui->labelIDFacepic_2->height());
    ui->labelIDFacepic_2->setPixmap(QPixmap::fromImage(__img));
}

// 添加照片
void MainFunction::on_pushButtonAddPic_clicked()
{
    ui->lablePic->clear();
    ui->lablePicResult_1->clear();
    ui->lablePicResult_2->clear();
    ui->lablePicResult_3->clear();
    ui->lablePicResult_4->clear();

    QString imgPath = QFileDialog::getOpenFileName(this,
                                                   tr("选择图片"),
                                                   "./",
                                                   tr("图片文件(*png *jpg)"));
    if(!imgPath.isEmpty())
    {
        addPic = cv::imread(imgPath.toStdString());
        QImage _img, __img;
        cvtColor(addPic, addPic, cv::COLOR_BGR2RGB);
        _img  = QImage((const unsigned char*)addPic.data, addPic.cols, addPic.rows, addPic.step, QImage::Format_RGB888);
        __img = _img.scaled(ui->lablePic->width(),ui->lablePic->height());
        ui->lablePic->setPixmap(QPixmap::fromImage(__img));
    }
    else
    {
        qDebug() << "NOT FOUND PIC!";
    }

}

//图片查找
void MainFunction::on_pushButtonFind_clicked()
{
    //遍历文件夹
    QString dirPath = QDir::currentPath() + "/pic/find_t/"; // !
    QStringList list;
    QDirIterator it(dirPath, QStringList() << "*.jpg" << "*.png", QDir::Files | QDir::NoSymLinks | QDir::NoDotAndDotDot, QDirIterator::Subdirectories);
    while(it.hasNext())
    {
       it.next();
       list.append(it.fileInfo().absoluteFilePath());
    }
    cv::Mat t;
    std::map<float, QString, greater<float>> mp;
    for(QString &c : list)
    {
        t = cv::imread(c.toStdString());
        mp[allTools::getFaceCmp(addPic, t)] = c;
    }
    int times = 1;
    QImage _img, __img;
    for(auto &c : mp)
    {
        if(times > 4) break;
        t = cv::imread(c.second.toStdString());
        cvtColor(t, t, cv::COLOR_BGR2RGB);
        _img  = QImage((const unsigned char*)t.data, t.cols, t.rows, t.step, QImage::Format_RGB888);
        if(times == 1)
        {
            __img = _img.scaled(ui->lablePicResult_1->width(),ui->lablePicResult_1->height());
            ui->lablePicResult_1->setPixmap(QPixmap::fromImage(__img));
        }
        else if(times == 2)
        {
            __img = _img.scaled(ui->lablePicResult_2->width(),ui->lablePicResult_2->height());
            ui->lablePicResult_2->setPixmap(QPixmap::fromImage(__img));
        }
        else if(times == 3)
        {
            __img = _img.scaled(ui->lablePicResult_3->width(),ui->lablePicResult_3->height());
            ui->lablePicResult_3->setPixmap(QPixmap::fromImage(__img));
        }
        else if(times == 4)
        {
            __img = _img.scaled(ui->lablePicResult_4->width(),ui->lablePicResult_4->height());
            ui->lablePicResult_4->setPixmap(QPixmap::fromImage(__img));
        }
        times++;
    }

}

//清空条件
void MainFunction::on_pushButtonClear_clicked()
{
    ui->lineEditName_2->clear();
    ui->dateTimeEditStart->clear();
    ui->dateTimeEditEnd->clear();
}

//查找日志
void MainFunction::on_pushButtonSearch_clicked()
{
    QString userId = ui->lineEditName_2->text();
    QString startData = ui->dateTimeEditStart->text();
    QString endData = ui->dateTimeEditEnd->text();

    int pos = 0;
    while(startData[pos] != ' ')
    {
        if(startData[pos] == '/') startData[pos] = '.';
        pos ++;
    }
    startData = QString::fromStdString(startData.toStdString().substr(0, pos));
    pos = 0;
    while(endData[pos] != ' ')
    {
        if(endData[pos] == '/') endData[pos] = '.';
        pos ++;
    }
    endData = QString::fromStdString(endData.toStdString().substr(0, pos));
    qDebug() << userId << ' ' << startData << ' ' << endData;

    QMap<QString, QMap<QString, QString>> t = allTools::getLogInfo(startData, endData, userId);
    ModelDB->clear();
    //表头均匀
    ui->tableViewResult->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    //单元格不可编辑
    ui->tableViewResult->setEditTriggers(QAbstractItemView::NoEditTriggers);
    //去除序列号
    ui->tableViewResult->verticalHeader()->setHidden(true);
    QStringList headerLable;
    headerLable << "用户ID" << "时间" << "人脸识别结果" << "设备IP";

    //add Info
    if(t.isEmpty())
    {
        ModelDB->setRowCount(1);
        ModelDB->setColumnCount(1);
        ModelDB->setData(ModelDB->index(0, 0), "未找到任何记录", Qt::DisplayRole);
        ModelDB->item(0,0)->setTextAlignment(Qt::AlignCenter); //内容居中
    }
    else
    {
        ModelDB->setRowCount(t.size());
        ModelDB->setColumnCount(4);
        ModelDB->setHorizontalHeaderLabels(headerLable);
        auto j = t.begin();
        for(int i=0;i<t.size();i++)
        {
            ModelDB->setData(ModelDB->index(i, 0), j->value("userId"), Qt::DisplayRole);
            ModelDB->item(i,0)->setTextAlignment(Qt::AlignCenter);
            ModelDB->setData(ModelDB->index(i, 1), j->value("time"), Qt::DisplayRole);
            ModelDB->item(i,1)->setTextAlignment(Qt::AlignCenter);
            ModelDB->setData(ModelDB->index(i, 2), j->value("result"), Qt::DisplayRole);
            ModelDB->item(i,2)->setTextAlignment(Qt::AlignCenter);
            ModelDB->setData(ModelDB->index(i, 3), j->value("IP"), Qt::DisplayRole);
            ModelDB->item(i,3)->setTextAlignment(Qt::AlignCenter);
            j ++;
        }
    }

    ui->tableViewResult->setModel(ModelDB);

}

// 录入表情
void MainFunction::on_pushButtonGet_clicked()
{
    if (!allTools::getCap()->isOpened())
    {
        allTools::getCap()->open(0);
        if(!allTools::getCap()->isOpened()) qDebug() << "Can not open a camera\n";
    }
    Mat img;
    QImage _img, __img;
    // Model Init
    ModelRes->clear();
    QStringList headerLable1;
    headerLable1 << "Emotion Get";
    ModelRes->setHorizontalHeaderLabels(headerLable1);
    ModelRes->setRowCount(1);
    ModelRes->setColumnCount(1);
    //tabview init
    ui->tableResult_2->verticalHeader()->setHidden(true); //去除序列号
    ui->tableResult_2->setFocusPolicy(Qt::NoFocus); // 去除选中虚线框
    ui->tableResult_2->horizontalHeader()->setStretchLastSection(true); //表头填充

    int res = 0;
    int times = 0;
    while (true)
    {
        if(capStatus == false) {capStatus = true; break;}
        *allTools::getCap() >> img;
        if (img.empty()) break;
        cv::flip(img, img, 1);

        //TabView 插入数据
        ModelRes->setData(ModelRes->index(0, 0), "开始录入!请做出表情!", Qt::DisplayRole);
        ModelRes->item(0,0)->setTextAlignment(Qt::AlignCenter); //内容居中
        ui->tableResult_2->setModel(ModelRes);

        res = allTools::emotion("CPU", img);
        if(res != 4 && res != -1)
        {
            if(times >= 10)
            {
                //update user_t
                allTools::updateEmotion(UserInfo["id"], QString::number(res));
                UserInfo = allTools::getDbUserInfo(UserInfo["id"]);


                QMessageBox t(this);
                t.setWindowTitle("提示");
                t.setText("录入成功！");
                t.addButton("确定",QMessageBox::AcceptRole);
                if(t.exec() == QMessageBox::AcceptRole) {}
                ui->previewlabel_2->clear();
                break;
            }
            times ++;
        }

        cvtColor(img, img, cv::COLOR_BGR2RGB);
        _img  = QImage((const unsigned char*)img.data, img.cols, img.rows, img.step, QImage::Format_RGB888);
        __img = _img.scaled(ui->previewlabel_2->width(),ui->previewlabel_2->height());
        ui->previewlabel_2->setPixmap(QPixmap::fromImage(__img));

        cv::waitKey(0);
    }
}

// 录入动作
void MainFunction::on_pushButtonGetAction_3_clicked()
{
    if (!allTools::getCap()->isOpened())
    {
        allTools::getCap()->open(0);
        if(!allTools::getCap()->isOpened()) qDebug() << "Can not open a camera\n";
    }
    Mat img;
    QImage _img, __img;
    // Model Init
    ModelRes->clear();
    QStringList headerLable1;
    headerLable1 << "FaceAction Get";
    ModelRes->setHorizontalHeaderLabels(headerLable1);
    ModelRes->setRowCount(1);
    ModelRes->setColumnCount(1);

    //tabview init
    ui->tableResult_5->verticalHeader()->setHidden(true); //去除序列号
    ui->tableResult_5->setFocusPolicy(Qt::NoFocus); // 去除选中虚线框
    ui->tableResult_5->horizontalHeader()->setStretchLastSection(true); //表头填充

    int res = 0;
    int _times = 1;
    QString resAction = "";
    while (true)
    {
        if(capStatus == false) {capStatus = true; break;}
        *allTools::getCap() >> img;
        if (img.empty()) break;
        cv::flip(img, img, 1);

        if(_times == 1)
        {
            ModelRes->setData(ModelRes->index(0, 0), "请做出第一个动作!", Qt::DisplayRole);
            ModelRes->item(0,0)->setTextAlignment(Qt::AlignCenter); //内容居中
            ui->tableResult_5->setModel(ModelRes);

            res = allTools::getFaceActionId(img);
            if(res != 0)
            {
                ui->checkBox->setChecked(true);
                resAction += QString::number(res);
                ++_times;
            }

        }
        else if(_times == 2)
        {
            ModelRes->setData(ModelRes->index(0, 0), "请做出第二个动作!", Qt::DisplayRole);
            ModelRes->item(0,0)->setTextAlignment(Qt::AlignCenter); //内容居中
            ui->tableResult_5->setModel(ModelRes);

            res = allTools::getFaceActionId(img);
            if(res != 0)
            {
                ui->checkBox->setChecked(false);
                ui->checkBox_2->setChecked(true);
                resAction += QString::number(res);
                ++_times;
            }
        }
        else if(_times == 3)
        {
            ModelRes->setData(ModelRes->index(0, 0), "请做出第三个动作!", Qt::DisplayRole);
            ModelRes->item(0,0)->setTextAlignment(Qt::AlignCenter); //内容居中
            ui->tableResult_5->setModel(ModelRes);

            res = allTools::getFaceActionId(img);
            if(res != 0)
            {
                ui->checkBox_2->setChecked(false);
                ui->checkBox_3->setChecked(true);
                resAction += QString::number(res);
                ++_times;
            }

        }
        else if(_times == 4)
        {
            //update user_t
            allTools::updateAction(UserInfo["id"], resAction);
            UserInfo = allTools::getDbUserInfo(UserInfo["id"]);

            QMessageBox t(this);
            t.setWindowTitle("提示");
            t.setText("录入成功！");
            t.addButton("确定",QMessageBox::AcceptRole);
            if(t.exec() == QMessageBox::AcceptRole) {}
            ui->checkBox_3->setChecked(false);
            ui->previewlabel_5->clear();
            _times = 1;
            break;
        }

        cvtColor(img, img, cv::COLOR_BGR2RGB);
        _img  = QImage((const unsigned char*)img.data, img.cols, img.rows, img.step, QImage::Format_RGB888);
        __img = _img.scaled(ui->previewlabel_5->width(),ui->previewlabel_5->height());
        ui->previewlabel_5->setPixmap(QPixmap::fromImage(__img));

        cv::waitKey(0);
    }
}

